package cn.imvc.app.models;

import java.util.Collection;
import java.util.LinkedHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Goods;
import cn.imvc.app.entities.GoodsImage;
import cn.imvc.app.entities.GoodsSpecValue;
import cn.imvc.app.repositories.GoodsImageRepository;
import cn.imvc.app.repositories.GoodsRepository;
import cn.imvc.app.repositories.GoodsSpecValueRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;

@Service
public class GoodsImageModelImpl implements GoodsImageModel {

	@Autowired
	GoodsImageRepository goodsImageRepository;
	@Autowired
	GoodsRepository goodsRepository;
	
	public LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> getRequestMap() {
		// TODO Auto-generated method stub
		return null;
	}

	public Page<GoodsImage> find(ViewRequest viewRequest) {
		if(viewRequest == null){
			viewRequest=new ViewRequest();
		}
		viewRequest.getSort().put("sort", "asc");
		return goodsImageRepository.findAll(ModelUtil.OrderByIdDesc(viewRequest));
	}

	public GoodsImage get(int id) {
		return goodsImageRepository.findOne(id);
	}

	public GoodsImage save(GoodsImage goodsImage) {
		Goods goods = goodsRepository.getOne(goodsImage.getGoods().getId());
		goodsImage.setGoods(goods);
		if(goodsImage.getGoodsSpecValue().getId() == 0){
			goodsImage.setGoodsSpecValue(null);
		}
		return goodsImageRepository.saveAndFlush(goodsImage);
	}

	public GoodsImage update(GoodsImage goodsImage) {
		Goods goods = goodsRepository.getOne(goodsImage.getGoods().getId());
		goodsImage.setGoods(goods);
		if(goodsImage.getGoodsSpecValue().getId() == 0){
			goodsImage.setGoodsSpecValue(null);
		}
		return goodsImageRepository.saveAndFlush(goodsImage);
	}

	public void delete(int id) {
		goodsImageRepository.delete(id);
	}

	public void deleteBatch(int[] ids) {
		for (int id : ids) {
			delete(id);
		}
	}

	public void deleteByGoodsSpecValue(GoodsSpecValue goodsSpecValue) {
		goodsImageRepository.deleteBygoodsSpecValue(goodsSpecValue);
	}

}
